﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WLYT.Application.Interfaces;
using WLYT.Core;
using WLYT.Domain.Entries;
using WLYT.Domain.Model;
using Newtonsoft.Json;
using WLYT.Common;
using WLYT.Domain.Enum;

namespace WLYT.Application.Services
{
    public class InventoryService(IRepository<Inventory> inventoryRepository, IRepository<InventoryLog> inventoryLogRepository) : IInventoryService
    {
        public async Task<List<Inventory>> GetListAsync(List<string> reelList)
        {
            return await inventoryRepository.GetListAsync(p => reelList.Contains(p.ReelId) && p.Status == 0);
        }

        public async Task UpdateAsync(List<string> reelList)
        {
            await inventoryRepository.UpdateAsync(p => new Inventory { Status = (int)InventoryStatus.Lock }, p => reelList.Contains(p.ReelId) && p.Status == 0);
        }

        public async Task<ApiResult> InStock(SMTModel model)
        {
            ApiResult result = new();
            var inventory = await inventoryRepository.GetFirstAsync(p => p.ReelId == model.ReelId);
            if (inventory != null)
            {
                await inventoryRepository.DeleteAsync(inventory);
            }
            inventory = new Inventory
            {
                ReelId = model.ReelId,
                LocationNo = model.LocationNo,
                WarehouseNo = model.WarehouseNo,
                OriginalCode = model.OriginalCode,
            };
            await inventoryRepository.InsertAsync(inventory);
            await inventoryLogRepository.InsertAsync(new InventoryLog
            {
                OrderType = (int)InventoryType.入库,
                ReelId = inventory.ReelId,
                LocationNo = inventory.LocationNo,
                WarehouseNo = inventory.WarehouseNo,
                OriginalCode = model.OriginalCode,
            });
            return result;
        }

        public async Task OutStock(string reelId, string orderNo = "", InventoryType type = InventoryType.出库)
        {
            var inventory = await inventoryRepository.GetFirstAsync(p => p.ReelId == reelId);
            if (inventory == null) return;
            await inventoryRepository.DeleteAsync(inventory);
            await inventoryLogRepository.InsertAsync(new InventoryLog
            {
                OrderType = (int)type,
                ReelId = inventory.ReelId,
                LocationNo = inventory.LocationNo,
                WarehouseNo = inventory.WarehouseNo,
                OriginalCode = inventory.OriginalCode,
                OrderNo = orderNo,
            });
        }
    }
}
